import { createStore } from 'vuex'
import * as auth from '../api/auth'
import * as article from '../api/article'
import * as qa from '../api/qa'

const store = createStore({
  state: {
    user: null,
    token: localStorage.getItem('token') || null,
    articles: [],
    currentArticle: null,
    questions: [],
    currentQuestion: null
  },

  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    clearAuth(state) {
      state.user = null
      state.token = null
      localStorage.removeItem('token')
    },
    setArticles(state, articles) {
      state.articles = articles
    },
    setCurrentArticle(state, article) {
      state.currentArticle = article
    },
    setQuestions(state, questions) {
      state.questions = questions
    },
    setCurrentQuestion(state, question) {
      state.currentQuestion = question
    }
  },

  actions: {
    async login({ commit }, credentials) {
      const response = await auth.login(credentials)
      commit('setToken', response.token)
      commit('setUser', response.user)
      return response
    },

    async register({ commit }, userData) {
      const response = await auth.register(userData)
      commit('setToken', response.token)
      commit('setUser', response.user)
      return response
    },

    async fetchUserInfo({ commit }) {
      try {
        const response = await auth.getUserInfo()
        console.log('获取到的用户信息:', response)
        
        // 尝试从不同可能的响应结构中获取用户数据
        const userData = response.user || response.data || response
        
        // 验证用户数据是否包含必要的字段
        if (userData && (userData._id || userData.id)) {
          // 标准化用户数据结构
          const normalizedUser = {
            _id: userData._id || userData.id,
            username: userData.username,
            email: userData.email,
            avatar: userData.avatar,
            ...userData
          }
          commit('setUser', normalizedUser)
          return response
        }
        
        console.error('无效的用户数据结构:', userData)
        throw new Error('无效的用户信息格式')
      } catch (error) {
        console.error('获取用户信息失败:', error)
        commit('clearAuth')
        throw error
      }
    },

    logout({ commit }) {
      commit('clearAuth')
    },

    // 文章相关
    async fetchArticles({ commit }) {
      const response = await article.getArticles()
      commit('setArticles', response.articles)
      return response
    },

    async fetchArticleById({ commit }, id) {
      try {
        if (!id) {
          throw new Error('文章ID不能为空')
        }
        const response = await article.getArticleById(id)
        console.log('获取到的文章详情:', response);
        
        if (!response) {
          throw new Error('文章不存在')
        }
        commit('setCurrentArticle', response)
        return response
      } catch (error) {
        console.error('获取文章详情失败：', error)
        commit('setCurrentArticle', null)
        throw error
      }
    },

    async createArticle({ dispatch }, articleData) {
      const response = await article.createArticle(articleData)
      await dispatch('fetchArticles')
      return response
    },

    async likeArticle({ dispatch }, id) {
      const response = await article.likeArticle(id)
      await dispatch('fetchArticleById', id)
      return response
    },

    async createComment({ dispatch }, { articleId, content }) {
      const response = await article.createComment(articleId, { content })
      await dispatch('fetchArticleById', articleId)
      return response
    },

    // 问答相关
    async fetchQuestions({ commit }, params) {
      try {
        const response = await qa.getQuestions(params)
        commit('setQuestions', response.questions)
        return response
      } catch (error) {
        console.error('获取问题列表失败：', error)
        commit('setQuestions', [])
        return { questions: [], total: 0 }
      }
    },

    async fetchQuestionById({ commit }, id) {
      try {
        const response = await qa.getQuestionById(id)
        commit('setCurrentQuestion', response.question)
        return response
      } catch (error) {
        console.error('获取问题详情失败：', error)
        commit('setCurrentQuestion', null)
        throw error
      }
    },

    async createQuestion({ dispatch }, questionData) {
      try {
        const response = await qa.createQuestion(questionData)
        await dispatch('fetchQuestions')
        return response
      } catch (error) {
        console.error('创建问题失败：', error)
        throw error
      }
    },

    async createAnswer({ dispatch }, { questionId, content }) {
      try {
        const response = await qa.createAnswer(questionId, { content })
        await dispatch('fetchQuestionById', questionId)
        return response
      } catch (error) {
        console.error('回答问题失败：', error)
        throw error
      }
    }
  },

  getters: {
    isAuthenticated: state => !!state.token,
    currentUser: state => state.user || null,
    getArticles: state => state.articles,
    getCurrentArticle: state => state.currentArticle,
    getQuestions: state => state.questions,
    getCurrentQuestion: state => state.currentQuestion
  }
})

export default store 